package com.liulishuo.magicprogress.demo.widget;

import com.liulishuo.magicprogresswidget.ISmoothTarget;
import com.liulishuo.magicprogresswidget.MyValueAnimator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Text;
import ohos.app.Context;

/**
 * Created by Jacksgong on 12/11/15.
 */
public class AnimTextView extends Text implements ISmoothTarget {

    private int progress;
    private int max = 100;
    private float lastPercent;
    private MyValueAnimator animatorValue;
    private long maxTime = 4000;

    public AnimTextView(Context context) {
        super(context);
    }

    public AnimTextView(Context context, AttrSet attrSet) {
        super(context, attrSet);
    }

    public AnimTextView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    public void setProgress(final int progress) {
        this.progress = progress;
        setText(String.valueOf(progress));
    }

    public int getProgress() {
        return this.progress;
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }

    @Override
    public float getPercent() {
        return getProgress() / (float) getMax();
    }

    @Override
    public void setPercent(float percent) {
        percent = percentIn01(percent);
        anim(0, percent, (long) (percent * maxTime));
    }

    @Override
    public void setPercent(float percent, long durationMillis) {
        percent = percentIn01(percent);
        anim(0, percent, durationMillis);
    }

    @Override
    public void setSmoothPercent(float percent) {
        percent = percentIn01(percent);
        anim(lastPercent, percent, (long) ((percent - lastPercent) * maxTime));
    }

    @Override
    public void setSmoothPercent(float percent, long durationMillis) {
        percent = percentIn01(percent);
        anim(lastPercent, percent, durationMillis);
    }

    private void anim(float lastPercent, float percent, long duration) {
        if (animatorValue != null) {
            if (animatorValue.isRunning()) {
                animatorValue.end();
            }
            animatorValue.release();
        }
        animatorValue = MyValueAnimator.ofFloat(lastPercent, percent);
        animatorValue.setDuration(duration);
        animatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float value) {
                setProgress((int) Math.ceil(value * getMax()));
            }
        });
        animatorValue.start();
        this.lastPercent = percent;
    }

    private float percentIn01(float percent) {
        percent = Math.min(1, percent);
        percent = Math.max(0, percent);
        return percent;
    }

}
